<template>
  <div class="app-container">


    <el-row :gutter="20">
      <el-col :span="12" :xs="24">
        <el-card class="box-card" :body-style="{ padding: '0px' }">
          <div class="amap-page-container">
            <div style="position: absolute">
              <el-amap-search-box class="search-box" :search-option="searchOption" :on-search-result="onSearchResult"></el-amap-search-box>
            </div>
            <el-amap vid="amapDemo" :center="mapCenter" :zoom="zoom" :events="events" class="amap-demo">
              <el-amap-marker v-for="(marker, index) in markers" :position="marker.position" :events="marker.events" :vid="index" :title="marker.title" :offset="marker.offset" :icon="marker.icon"></el-amap-marker>
              <el-amap-marker v-for="(marker, index) in modifymarker" draggable="true" :position="marker.position" :events="marker.events" :vid="index" :title="marker.title" :offset="marker.offset"  icon="http://yishoutong.hbweiyinqing.cn/prod-api/app/files/red.png" zIndex="200"></el-amap-marker>
            </el-amap>
          </div>
        </el-card>
      </el-col>
      <!--用户数据-->
      <el-col :span="12" :xs="24">
        <el-card class="box-card" >
          <div class="amap-page-container" style="overflow:auto">
            <el-form ref="form" :model="form" label-width="100px" >
              <el-divider content-position="left">基础信息</el-divider>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="店铺名称" prop="title">
                    <el-input v-model="form.title" placeholder="请输入公司名称" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="经度" prop="title">
                    <el-input v-model="form.lng" placeholder="请输入公司名称" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="纬度" prop="deptId">
                    <el-input v-model="form.lat" placeholder="请输入公司名称" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="门头照" prop="companyPic">
                    <!--<el-input v-model="form.companyPic" placeholder="请输入门头照" />-->
                    <el-upload
                      class="avatar-uploader"
                      action="https://jsonplaceholder.typicode.com/posts/"
                      :show-file-list="false"
                      :on-success="(response, file, fileList) => handleSuccess(response, file, fileList, '1')"
                      :http-request="uploadCompnayPic">
                      <img v-if="form.companyPic" :src="'../prod-api/app/files/' + form.companyPic" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="营业执照" prop="licensePic">
                    <el-upload
                      class="avatar-uploader"
                      action="https://jsonplaceholder.typicode.com/posts/"
                      :show-file-list="false"
                      :on-success="(response, file, fileList) => handleSuccess(response, file, fileList, '2')"
                      :http-request="uploadLicense">
                      <img v-if="form.licensePic" :src="'../prod-api/app/files/' + form.licensePic" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                  </el-form-item>

                </el-col>
              </el-row>

              <el-divider content-position="left">营业执照</el-divider>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="公司名称" prop="companyName">
                    <el-input v-model="form.companyName" placeholder="请输入公司名称" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="公司法人" prop="name">
                    <el-input v-model="form.name" placeholder="请输入公司法人" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="联系方式" prop="mobile">
                    <el-input v-model="form.mobile" placeholder="请输入联系方式" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="公司地址" prop="address">
                    <el-input v-model="form.address" placeholder="请输入公司地址" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="执照编号" prop="businessCode">
                    <el-input v-model="form.businessCode" placeholder="请输入执照编号" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">

                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="经营范围">
                    <el-input
                      type="textarea"
                      :autosize="{ minRows: 4, maxRows: 4}"
                      placeholder="请输入经营范围"
                      v-model="form.businessScope">
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>



              <el-divider content-position="left">缴费信息</el-divider>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="是否免征">
                    <el-radio-group v-model="form.costType">
                      <el-radio
                        v-for="dict in costTypeOptions"
                        :key="dict.dictValue"
                        :label="dict.dictValue"
                      >{{dict.dictLabel}}</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="公司类型" v-if="form.costType == '0'">
                    <el-radio-group v-model="form.costCompnayType" @change="changeHandlerType">
                      <el-radio
                        v-for="item in allprojectList"
                        :key="item.id"
                        :label="item.id"
                      >{{item.name}}</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="收费分类" v-if="form.costType == '0'">
                    <el-select v-model="form.projectId" placeholder="请选择收费分类" @change="changeHandlerProject">
                      <el-option
                        v-for="project in costProjectList"
                        :key="project.id"
                        :label="project.name"
                        :value="project.id"
                      />
                    </el-select>
                    <div v-for="project in categoryRateList">区间(元):{{project.minNum}}-{{project.maxNum}}  &nbsp;&nbsp;单价:{{project.money}}元/{{project.unit}}</div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="收费标准" prop="costStandard" v-if="form.costType == '0'">
                    <el-input v-model="form.costStandard" placeholder="请输入收费标准" @blur="costStandard"/>
                  </el-form-item>

                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="应收金额" prop="totalMoney" v-if="form.costType == '0'">
                    <el-input v-model="form.totalMoney" placeholder="请输入应收金额" @blur="totalMoney"/>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="已缴费金额" prop="money" v-if="form.costType == '0'">
                    <el-input v-model="form.money" placeholder="请输入目前已缴费金额" />
                  </el-form-item>
                </el-col>
              </el-row>


              <el-divider content-position="left">清运单位</el-divider>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="清运单位" prop="clearUnit">
                    <el-radio-group v-model="form.clearUnit">
                      <el-radio
                        v-for="dict in clearUnitOptions"
                        :key="dict.dictValue"
                        :label="dict.dictValue"
                      >{{dict.dictLabel}}</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="垃圾生产量" prop="clearNum">
                    <el-input v-model="form.clearNum" placeholder="请输入垃圾生产量" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="联系人姓名" prop="clearName">
                    <el-input v-model="form.clearName" placeholder="请输入联系人姓名" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="联系人方式" prop="clearMobile">
                    <el-input v-model="form.clearMobile" placeholder="请输入联系人姓名" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="公司名称" prop="clearCompanyName">
                    <el-input v-model="form.clearCompanyName" placeholder="请输入清运公司名称" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">

                </el-col>
              </el-row>

              <el-row>
                <el-col :span="24" align="center">
                  <el-button type="primary" @click="submitForm">确 定</el-button>
                  <el-button @click="cancel">重 置</el-button>
                  <br />
                  &nbsp;
                </el-col>
              </el-row>

            </el-form>
          </div>
        </el-card>


      </el-col>
    </el-row>
  </div>
</template>

<script>
  import { queryPointList, getAppcostcompany, delAppcostcompany, addAppcostcompany, updateAppcostcompany , uploadCompnayPic,uploadLicense , queryCostProjectList} from "@/api/app/appcostcompany";

  export default {
    name: "Appcostcompany",
    data() {
      let self = this;
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 店铺管理表格数据
        appcostcompanyList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          cid: undefined,
          cname: undefined,
          cmoney: undefined,
          cunit: undefined,
          cmin: undefined,
          cmax: undefined,
          projectId: undefined,
          projectName: undefined,
          title: undefined,
          companyPic: undefined,
          lat: undefined,
          lng: undefined,
          licensePic: undefined,
          name: undefined,
          mobile: undefined,
          address: undefined,
          businessScope: undefined,
          businessCode: undefined,
          costType: undefined,
          costCompnayType: undefined,
          costStandard: undefined,
          totalMoney: undefined,
          money: undefined,
          clearUnit: undefined,
          clearNum: undefined,
          clearName: undefined,
          clearMobile: undefined,
          clearCompanyName: undefined,
          hide: undefined,
          state: undefined,
          deptId: undefined,
          deptName: undefined,
        },
        // 表单参数
        form: {},
        clearUnitOptions:[],
        costTypeOptions:[],
        allprojectList:[],
        costProjectList:[],
        categoryRateList:[],
        // 表单校验
        checkLngLat:"",
        rules: {
          title: [
            { required: true, message: "公司名称不能为空", trigger: "blur" }
          ],
          companyPic: [
            { required: true, message: "门头照不能为空", trigger: "blur" }
          ],
          createTime: [
            { required: true, message: "创建时间不能为空", trigger: "blur" }
          ]
        },
        // 高德地图
        events: {
          init(o) {
            console.log("初始化高德地图1")
          },
          click(e) {
            let {lng, lat} = e.lnglat;
            self.checkLngLat = lng + "," +lat;
            console.log(lng + "," +lat);
            self.modifymarker[0].position = [lng, lat];
            self.form.lng = lng;
            self.form.lat = lat;
            // self.currLatLng = e.lnglat.lng + ","+e.lnglat.lat;
            // console.log(self.currLatLng);
            // self.addPolygonLatLng(e.lnglat.lng, e.lnglat.lat);

          }
        },
        markers: [

        ],
        modifymarker: [{
          position: [114.49201298589513, 36.62777068436099],
          offset: [-20, -28],
          events: {
            dragend: (e) => {
              let {lng, lat} = e.lnglat;
              self.checkLngLat = lng + "," +lat;
              console.log(lng + "," +lat);
              self.modifymarker[0].position = [lng, lat];
              self.form.lng = lng;
              self.form.lat = lat;
            }
          }
        }],
        searchOption: {
          city: '邯郸',
          citylimit: true
        },
        zoom: 20,
        mapCenter: [114.494707,36.61089],
        index: 0
      };
    },
    created() {
      this.queryPointList();
      this.queryCostProjectList();
      this.getDicts("app_clear_unit").then(response => {
        this.clearUnitOptions = response.data;
      });
      this.getDicts("app_cost_type").then(response => {
        this.costTypeOptions = response.data;
      });
      this.reset();
    },
    methods: {
      /** 查询店铺管理列表 */
      queryPointList() {
        let that = this;
        this.loading = true;
        queryPointList(that.queryParams).then(response => {
          //this.appcostcompanyList = response.data;
          this.loading = false;
          setTimeout(function () {
            response.data.forEach(function (item, index, array) {

              if(index == 0){
                that.mapCenter = [item.x, item.y];
              }
              var color = "";
              if(item.state == "3"){
                color = "http://yishoutong.hbweiyinqing.cn/prod-api/app/files/blue3.png";
              }else if(item.state == "2"){
                color = "http://yishoutong.hbweiyinqing.cn/prod-api/app/files/blue2.png";
              }else{
                color = "http://yishoutong.hbweiyinqing.cn/prod-api/app/files/blue1.png";
              }
              that.addMarker(item.id, item.title, item.x, item.y, color, that.index);
              that.index++;
              console.log(item.title + "==" + item.state + "=" + that.index);
            });
          }, 100);

        });
      },
      queryCostProjectList() {
        this.loading = true;
        queryCostProjectList().then(response => {
          this.allprojectList = response.data;
          console.log(this.allprojectList);
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          cid: undefined,
          cname: undefined,
          cmoney: undefined,
          cunit: undefined,
          cmin: undefined,
          cmax: undefined,
          projectId: undefined,
          projectName: undefined,
          title: undefined,
          companyPic: undefined,
          lat: '',
          lng: '',
          licensePic: undefined,
          compnayName: '',
          name: undefined,
          mobile: undefined,
          address: undefined,
          businessScope: undefined,
          businessCode: undefined,
          costType: "0",
          costCompnayType: undefined,
          costStandard: undefined,
          totalMoney: undefined,
          money: undefined,
          clearUnit: undefined,
          clearNum: undefined,
          clearName: undefined,
          clearMobile: undefined,
          clearCompanyName: undefined,
          hide: undefined,
          delFlag: undefined,
          remark: undefined,
          state: undefined,
          deptId: undefined,
          deptName: undefined,
          createBy: undefined,
          createTime: undefined
        };
        this.currLatLng = "";
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!=1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();

        this.open = true;
        this.title = "添加店铺管理";
      },
      /** 修改按钮操作 */
      handleUpdate(id, index) {
        console.log(id + "=" + index);
        this.reset();

        getAppcostcompany(id).then(response => {
          var that = this;
          that.form = response.data;
          that.form.index = index;
          console.log(JSON.stringify(response.data));
          if(that.form.lat && that.form.lng){
            that.currLatLng = that.form.lat + "," + that.form.lng;

            setTimeout(function () {
              console.log(that.currLatLng);
              console.log("********************");
              //that.addMarker(that.form.lng, that.form.lat);
              that.modifymarker[0].position = [that.form.lng, that.form.lat];
            }, 300);

          }
          this.allprojectList.forEach(function (item, index, array) {
            if(that.form.costCompnayType){
              console.log( item.id + "=" + that.form.costCompnayType);
              if(item.id == that.form.costCompnayType){
                that.costProjectList = item.children;
              }
            }
          });
          that.costProjectList.forEach(function (item, index, array) {
            if(item.id == that.form.projectId){
              console.info(JSON.stringify(item)); //当前元素的值
              that.categoryRateList = item.children;
              console.log(that.categoryRateList);
              console.log("------------changeHandlerProject--------------");
            }
          });
          this.open = true;
          this.title = "修改店铺管理";
        });
      },
      /** 提交按钮 */
      submitForm: function() {
        let that = this;
        that.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              updateAppcostcompany(this.form).then(response => {
                if (response.code === 200) {
                  that.msgSuccess("修改成功");
                  console.log(that.markers[that.form.index].position);
                  var color = "";
                  if(response.state == "3"){
                    color = "http://yishoutong.hbweiyinqing.cn/prod-api/app/files/blue3.png";
                  }else if(response.state == "2"){
                    color = "http://yishoutong.hbweiyinqing.cn/prod-api/app/files/blue2.png";
                  }else{
                    color = "http://yishoutong.hbweiyinqing.cn/prod-api/app/files/blue1.png";
                  }
                  that.markers[that.form.index].position = that.modifymarker[0].position;
                  that.markers[that.form.index].icon = color;
                  this.reset();
                  //this.open = false;
                  //this.getList();
                }
              });
            } else {
              addAppcostcompany(this.form).then(response => {
                if (response.code === 200) {
                  that.msgSuccess("新增成功");
                  //this.addMarker(item.id, item.title, item.x, item.y);
                  var color = "";
                  if(response.state == "3"){
                    color = "http://yishoutong.hbweiyinqing.cn/prod-api/app/files/blue3.png";
                  }else if(response.state == "2"){
                    color = "http://yishoutong.hbweiyinqing.cn/prod-api/app/files/blue2.png";
                  }else{
                    color = "http://yishoutong.hbweiyinqing.cn/prod-api/app/files/blue1.png";
                  }
                  that.addMarker(response.id, this.form.title, this.form.lng, this.form.lat, color, that.index);
                  that.index++;
                  this.reset();
                }
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除店铺管理编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delAppcostcompany(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('app/appcostcompany/export', {
          ...this.queryParams
        }, `app_appcostcompany.xlsx`)
      },
      // 高德地图搜索功能
      addMarker: function(id, title, lng, lat, icon, index) {
        var that = this;
        var marker = {};
        //http://yishoutong.hbweiyinqing.cn/prod-api/app/files/blue.png
        marker.icon = icon;
        marker.offset = [-20, -28];
        marker.position = [lng, lat];

        var events = {};
        events.click = function(){//添加方法
          if(id){
            that.handleUpdate(id,index);

          }else{
            that.handleAdd();
          }

        }
        marker.events = events;

        if(title){
          marker.title = title;
        }

        that.markers.push(marker);
        // this.markers = [];
        // this.markers.push([lng, lat]);
        // console.log("addMarker");
      },
      onSearchResult(pois) {
        //this.markers = [];
        if (pois.length > 0) {
          let {lng, lat} = pois[0];
          //this.markers.push([lng, lat]);
          this.mapCenter = [lng, lat];
          // pois.forEach(poi => {
          //   let {lng, lat} = poi;
          // });


        }
      },
      uploadCompnayPic(param) {
        var fileObj = param.file;
        // FormData 对象
        var formData = new FormData();
        // 文件对象
        formData.append("picfile", fileObj);
        uploadCompnayPic(formData)
          .then(response => {
            if (response.code === 200) {
              //this.msgSuccess("附件上传成功");
              //this.form.testifyFile = response.url;
              //上传成功 调用onSuccess方法，否则没有完成图标
              //处理自己的逻辑
              param.onSuccess(response);
              fileObj.url = response.url;
            } else {
              this.msgError(response.msg);
            }
          })
          .catch(err => {
            console.log(err);
          });
      },
      uploadLicense(param) {
        var fileObj = param.file;
        // FormData 对象
        var formData = new FormData();
        // 文件对象
        formData.append("picfile", fileObj);
        uploadLicense(formData)
          .then(response => {
            if (response.code === 200) {
              //this.msgSuccess("附件上传成功");
              //this.form.testifyFile = response.url;
              //上传成功 调用onSuccess方法，否则没有完成图标
              //处理自己的逻辑
              param.onSuccess(response);
              fileObj.url = response.url;
            } else {
              this.msgError(response.msg);
            }
          })
          .catch(err => {
            console.log(err);
          });
      },
      handlePreview(file) {
        this.form.uploadCompnayPic = file.url;
        console.log("---------------handlePreview--------------");
      },
      handleRemove(file, fileList) {
        console.log("---------------handleRemove--------------");
        // var that = this;
        // that.form.testifyFile = JSON.stringify(fileList);
        // console.log(that.form.testifyFile);
      },
      handleSuccess(response, file, fileList, type) {
        console.log(response);

        if(response.code && response.code == 200){
          if(type == "1"){
            this.form.companyPic = response.data;
          }else if(type == "2"){
            this.form.licensePic = response.data;
          }

        }
      },
      handlePictureCardPreview(file) {
        this.form.licensePic = file.url;
      },
      changeHandlerType(value) {
        console.log('改变之后的值是:' + value)
        var that = this;
        this.allprojectList.forEach(function (item, index, array) {
          if(item.id == value){
            console.info(JSON.stringify(item)); //当前元素的值
            that.costProjectList = item.children;
            console.log(that.costProjectList);
            console.log("-------------changeHandlerType-------------");
          }
        });
      },
      changeHandlerProject(value) {
        console.log('改变之后的值是:' + value)
        var that = this;
        this.costProjectList.forEach(function (item, index, array) {
          if(item.id == value){
            console.info(JSON.stringify(item)); //当前元素的值
            that.categoryRateList = item.children;
            console.log(that.categoryRateList);
            console.log("------------changeHandlerProject--------------");
          }
        });
      },
      totalMoney(){
        let that = this;
        console.log("----------111111---------");
        if(that.categoryRateList){
          console.log("----------22222---------");
          if(that.categoryRateList.length == 1){
            console.log("----------33333---------");
            if(that.form.totalMoney > 0){
              console.log("----------444444---------");
              this.categoryRateList.forEach(function (item, index, array) {
                if(that.form.totalMoney){
                  that.form.costStandard = parseInt(that.form.totalMoney / item.money);
                }
              });
            }
          }
        }
      },
      costStandard(){
        let that = this;
        if(that.categoryRateList){
          if(that.form.costStandard > 0){
            this.categoryRateList.forEach(function (item, index, array) {
              that.form.totalMoney = item.money * that.form.costStandard;
            });
          }
        }
      }

    }
  };
</script>

<style >

  .search-box {
    position: absolute;
    top: 25px;
    left: 20px;
  }

  .amap-page-container {
    position: relative;
    width: 100%;
    height:calc(100vh - 130px);
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 140px;
    height: 140px;
    line-height: 140px;
    text-align: center;
  }
  .avatar {
    width: 140px;
    height: 140px;
    display: block;
  }
</style>
